package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private VMService vmService;

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     * @throws LogicException
     */
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        //新增工单表记录
        TaskEntity task = new TaskEntity();
        //获取售货机编码
        task.setTaskCode(generateTaskCode());
        //复制属性
        BeanUtils.copyProperties(taskViewModel, task);
        //修改工单状态为1：创建(待处理)
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //获取工单类型Id
        task.setProductTypeId(taskViewModel.getProductType());

        //跨服务查询售货机微服务   得到售货机的地址和区域id
        VmVO vo = vmService.getVMInfo(taskViewModel.getInnerCode());
        //获取 工单执行地址(点位地址)
        task.setAddr(vo.getNodeAddr());
        task.setRegionId(vo.getRegionId());
        this.save(task);

        updateTaskZSet(task, 1);

        return true;
    }


    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        //查询工单
        TaskEntity task = this.getById(id);
        //判断工单是否为状态1 待处理
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            //不是则抛出异常
            throw new LogicException("工单状态不是待处理");
        }
        //修改工单状态为2: 进行
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        return this.updateById(task);
    }


    /**
     * 取消工单
     *
     * @param id
     * @param cancelTaskViewModel
     * @return
     */
    @Override
    public boolean cancel(Long id, CancelTaskViewModel cancelTaskViewModel) {
        //查询工单
        TaskEntity task = this.getById(id);
        //判断工单状态是否为4:完成 或者 3:取消
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束");
        }
        //将工单状态修改为3: 取消
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        //获取工单取消设置的拒绝理由
        task.setDesc(cancelTaskViewModel.getDesc());
        updateTaskZSet(task, -1);
        return this.updateById(task);
    }

    @Autowired
    private MqttProducer mqttProducer;

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean complete(Long id) {
        //查询工单
        TaskEntity task = this.getById(id);
        //判断工单的状态是否为
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已经结束");
        }
        //修改工单状态为:4 完成
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(task);
        //判断 是 工单类型：投放工单 或者 工单类型：撤机工单
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || task.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            //运维工单封装
            noticeVMServiceStatus(task);
        }

        //判断是否为 工单类型: 补货工单
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            //补货工单封装
            noticeVMServiceSupply(task);
        }

        return true;
    }

    /**
     * 获取同一天内分配的工单最少的人
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode="1002";
        if(isRepair){ //如果是运维工单
            roleCode="1003";
        }
        String key= VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+ regionId+"."+roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 1);
        if(set==null || set.isEmpty()){
            throw  new LogicException("该区域暂时没有相关人员");
        }
        return (Integer) set.stream().collect( Collectors.toList()).get(0);
    }

    /**
     * 补货工单
     *
     * @param task
     */
    private void noticeVMServiceSupply(TaskEntity task) {
        //协议内容封装
        //1.根据工单id查询工单明细表
        QueryWrapper<TaskDetailsEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(TaskDetailsEntity::getTaskId, task.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(qw);
        //2.构建协议内容
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setInnerCode(task.getInnerCode());//售货机编号
        List<SupplyChannel> supplyChannels = Lists.newArrayList();//补货数据
        //从工单明细表提取数据加到补货数据中
        details.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            channel.setChannelId(d.getChannelCode());//货道编号
            channel.setCapacity(d.getExpectCapacity());//补货数量
            supplyChannels.add(channel);
        });
        supplyContract.setSupplyData(supplyChannels);

        //3.下发补货协议
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }


    /**
     * 运维工单
     *
     * @param task
     */
    private void noticeVMServiceStatus(TaskEntity task) {
        //向消息队列发送消息 通知售货机更改状态
        //建一个工单协议对象进行数据封装
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        //售货机编号
        taskCompleteContract.setInnerCode(task.getInnerCode());
        //工单类型
        taskCompleteContract.setTaskType(task.getProductTypeId());

        //下发运维工单
        //发送到emq
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单协议失败");
            throw new LogicException("发送工单协议失败");
        }

    }

    /**
     * 更新工单量列表
     *
     * @param taskEntity
     * @param score      增加的分值
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {
        String roleCode = "1003";//运维员
        if (taskEntity.getProductTypeId().intValue() == 2) {//如果是补货工单
            roleCode = "1002";//运营员
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);
    }


    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); //日期字符串
        String key = "Ikd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }


}
